package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean updateLocation(Long userId, Double longitude, Double latitude, String address) {
        try {
            long now = System.currentTimeMillis();
            Query query = Query.query(Criteria.where("userId").is(userId));
            UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
            if (location == null) {
                location = new UserLocation();
                location.setUserId(userId);
                location.setLocation(new GeoJsonPoint(longitude, latitude));
                location.setAddress(address);
                location.setCreated(now);
                location.setUpdated(now);
                location.setLastUpdated(now);
                mongoTemplate.save(location);
            } else {
                Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                        .set("updated", now)
                        .set("lastUpdated", location.getUpdated());
                mongoTemplate.updateFirst(query, update, UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Long> queryNearUser(Long userId, double distance) {
        //构造坐标点
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        if (location == null) {
            return null;
        }
        GeoJsonPoint point = location.getLocation();
        //构造半径
        Distance distanceObj = new Distance(distance/1000, Metrics.KILOMETERS);
        //画了一个圆圈
        Circle circle = new Circle(point, distanceObj);
        //构造query对象
        query = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);
        return CollUtil.getFieldValues(userLocations,"userId",Long.class);
    }
}
